package architect.springcloud.eureka.client;

import architect.springcloud.feign.factory.RestTemplateFactory;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 使用RestTemplate方式Controller
 *
 * @author guanxin
 * @date 2018/4/19 11:41
 */

@RestController
@RefreshScope
@Slf4j
public class RestTemplateController {

    @Value("${service.provider.uri}")
    private String serviceUrl;

    @Autowired
    // private RestTemplate restTemplate;
    private RestTemplateFactory restTemplateFactory;

    @Autowired
    private DiscoveryClient discoveryClient;

    @HystrixCommand(fallbackMethod = "getSmsFail")
    @GetMapping(value = "/index")
    public String index(@RequestParam String content) throws Exception {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        for (ServiceInstance si : instances) {
            log.info("host: {}, service_id: {}", si.getHost(), si.getServiceId());
        }
        log.info(serviceUrl);
        //restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("srv", "123456"));
        MultiValueMap<String, String> entity = new LinkedMultiValueMap<>();
        entity.add("content", content);
        //String result = restTemplate.postForObject(serviceUrl + "/sendSms", entity, String.class);
        String result = restTemplateFactory.getObject().postForObject(serviceUrl + "/sendSms", entity, String.class);
        log.info("response: {}", result);

        return result;
    }

    public String getSmsFail(String content) {
        return "Client call sendSms fail, content = " + content;
    }
}
